﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ZYStudios.Models;
using System.Collections.Specialized;
using DoubanApi;
using DoubanApi.Models;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ZYStudios.Common
{
    public sealed class PlaytimeHelper
    {
        static FileCacheProvider _MovieCache;
        private static FileCacheProvider CreateFileCache()
        {
            if (_MovieCache == null)
            {
                _MovieCache = new FileCacheProvider();
                NameValueCollection aAttribs = new NameValueCollection();
                aAttribs.Add("cachePath", "/MovieCache");
                _MovieCache.Initialize("MovieCache", aAttribs);
            }
            return _MovieCache;
        }


        private static DoubanApiClient CreateDoubanApi()
        {
            return new DoubanApiClient() { ApiKey = Properties.Settings.Default.ApiKey };
        }

        public static List<PlaytimeModel> GeneratePlayTime(Stream stream)
        {
            List<PlaytimeModel> aPlaytimeLine = new List<PlaytimeModel>();

            List<PlaytimeImportItemModel> aTempImportPlaytime = new List<PlaytimeImportItemModel>();

            Net.SourceForge.Koogra.Excel.Workbook aWookbook = new Net.SourceForge.Koogra.Excel.Workbook(stream);
            foreach (Net.SourceForge.Koogra.Excel.Worksheet aSheet in aWookbook.Sheets)
            {
                PlaytimeModel aPlaytime = new PlaytimeModel();
                aPlaytime.Id = Guid.NewGuid().ToString();
                aPlaytime.PlayData = aSheet.Name;
                aPlaytimeLine.Add(aPlaytime);
                aPlaytime.Movies = new List<PlaytimeItemModel>();
                aTempImportPlaytime = new List<PlaytimeImportItemModel>();
                bool IsFindTime = false, IsFindName = false;
                uint FindTimeCol = 0, FindNameCol = 0;
                for (uint i = aSheet.Rows.MinRow; i <= aSheet.Rows.MaxRow; i++)
                {
                    Net.SourceForge.Koogra.Excel.Row aRow = aSheet.Rows[i];
                    if (!aRow.IsEmpty())
                    {
                        if (!IsFindTime && !IsFindName)
                        {
                            for (uint j = aRow.Cells.MinCol; j <= aRow.Cells.MaxCol; j++)
                            {
                                Net.SourceForge.Koogra.Excel.Cell aCell = aRow.Cells[j];
                                string aValue = aCell.FormattedValue().Trim();
                                if (!string.IsNullOrEmpty(aValue))
                                {
                                    if (aValue == "开始")
                                    {
                                        IsFindTime = true;
                                        FindTimeCol = j;
                                    }

                                    if (aValue == "影片名称")
                                    {
                                        IsFindTime = true;
                                        FindNameCol = j;
                                    }
                                }
                            }
                        }
                        else
                        {
                            try
                            {
                                if (aRow.Cells[FindNameCol] != null && aRow.Cells[FindTimeCol] != null)
                                {
                                    string aMovieName = aRow.Cells[FindNameCol].FormattedValue().Trim();
                                    string aStartTime = aRow.Cells[FindTimeCol].Value.ToString().Trim();
                                    aStartTime = DateTime.FromOADate(double.Parse(aStartTime)).ToString("HH:mm");

                                    if (!string.IsNullOrEmpty(aMovieName) && !string.IsNullOrEmpty(aStartTime))
                                    {
                                        aTempImportPlaytime.Add(new PlaytimeImportItemModel()
                                        {
                                            MovieName = aMovieName,
                                            StartTime = aStartTime
                                        });
                                    }
                                }
                            }
                            catch (Exception)
                            {

                                throw;
                            }
                        }

                    }
                }

                var aMovieNames = aTempImportPlaytime.Select(p => p.MovieName).Distinct();
                foreach (var aMovieName in aMovieNames)
                {
                    var aPlaytimeItem = new PlaytimeItemModel();
                    var aMovieCachaProvider = CreateFileCache();

                    var aMovieCache = aMovieCachaProvider.Get(aMovieName.GetHashCode().ToString()) as MovieModel;
                    if (aMovieCache == null)
                    {
                        aPlaytimeItem.Movie = CreateDoubanApi().SearchMovie(aMovieName);
                        aPlaytimeItem.Movie.Title = aMovieName;
                        aMovieCachaProvider.Add(aMovieName.GetHashCode().ToString(), aPlaytimeItem.Movie, DateTime.Now.AddDays(2));
                        aMovieCachaProvider.Add(aPlaytimeItem.Movie.Id.ToString(), aPlaytimeItem.Movie, DateTime.Now.AddDays(2));
                    }
                    else
                    {
                        aPlaytimeItem.Movie = aMovieCache;
                    }

                    aPlaytimeItem.Movie.Title = aMovieName;



                    var aStartTimes = aTempImportPlaytime.Where(p => p.MovieName == aMovieName).Select(p => p.StartTime);
                    aStartTimes = aStartTimes.OrderBy<string, string>((p) => { return p; });

                    aStartTimes.ToList().ForEach(p => aPlaytimeItem.PlayTime += " " + p);


                    if (aPlaytimeItem.PlayTime.Length != 0)
                    {
                        aPlaytimeItem.PlayTime = aPlaytimeItem.PlayTime.Substring(1);
                    }
                    aPlaytimeItem.ParentId = aPlaytime.Id;
                    aPlaytimeItem.Id = Guid.NewGuid().ToString();
                    aPlaytimeItem.MovieDuration = aPlaytimeItem.Movie.Movie_Duration.ToString();
                    aPlaytimeItem.MovieName = aPlaytimeItem.Movie.Title;
                    aPlaytime.Movies.Add(aPlaytimeItem);
                }

            }

            return aPlaytimeLine;
        }

        public static List<PlaytimeModel> ReadPlayTimeData()
        {
            List<PlaytimeModel> data = new List<PlaytimeModel>();
            try
            {
                string aPath = HttpContext.Current.Server.MapPath("/App_Data/Playtime.bin");
                if (File.Exists(aPath))
                {
                    using (FileStream file = System.IO.File.OpenRead(aPath))
                    {
                        BinaryFormatter formatter = new BinaryFormatter();
                        data = (List<PlaytimeModel>)formatter.Deserialize(file);
                    }
                }
            }
            catch (Exception)
            {

            }
            return data;
        }

        public static void SavePlayTimeData(List<PlaytimeModel> aPlayTimeData)
        {
            using (FileStream file = System.IO.File.OpenWrite(HttpContext.Current.Server.MapPath("/App_Data/Playtime.bin")))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(file, aPlayTimeData);
            }
        }

        #region 2007
        //public static List<PlaytimeModel> GeneratePlayTime()
        //{
        //    List<PlaytimeModel> aPlaytimeLine = new List<PlaytimeModel>();


        //    List<PlaytimeImportItemModel> aTempImportPlaytime = new List<PlaytimeImportItemModel>();

        //    string aFileName = HttpContext.Current.Server.MapPath("/App_Data/Playtime.xlsx");
        //    if (System.IO.File.Exists(aFileName))
        //    {
        //        using (Stream stream = File.Open(aFileName, FileMode.Open, FileAccess.Read))
        //        {
        //            Net.SourceForge.Koogra.Excel2007.Workbook aWookbook = new Net.SourceForge.Koogra.Excel2007.Workbook(stream);
        //            foreach (Net.SourceForge.Koogra.Excel2007.Worksheet aSheet in aWookbook.GetWorksheets())
        //            {
        //                PlaytimeModel aPlaytime = new PlaytimeModel();
        //                aPlaytime.PlayData = aSheet.Name;
        //                aPlaytimeLine.Add(aPlaytime);
        //                aPlaytime.Movies = new List<PlaytimeItemModel>();
        //                aTempImportPlaytime = new List<PlaytimeImportItemModel>();
        //                for (uint i = 1; i <= aSheet.CellMap.LastRow; i++)
        //                {
        //                    Net.SourceForge.Koogra.Excel2007.Row aRow = aSheet.GetRow(i);
        //                    aTempImportPlaytime.Add(new PlaytimeImportItemModel()
        //                    {
        //                        MovieName = aRow.GetCell(3).GetFormattedValue(),
        //                        Location = aRow.GetCell(0).GetFormattedValue(),
        //                        StartTime = aRow.GetCell(1).GetFormattedValue(),
        //                        EndTime = aRow.GetCell(2).GetFormattedValue()
        //                    });
        //                }

        //                var aMovieNames = aTempImportPlaytime.Select(p => p.MovieName).Distinct();
        //                foreach (var aMovieName in aMovieNames)
        //                {
        //                    var aPlaytimeItem = new PlaytimeItemModel();

        //                    var aMovieCachaProvider = CreateFileCache();

        //                    var aMovieCache = aMovieCachaProvider.Get(aMovieName.GetHashCode().ToString()) as MovieModel;
        //                    if (aMovieCache == null)
        //                    {
        //                        aPlaytimeItem.Movie = CreateDoubanApi().SearchMovie(aMovieName);
        //                        aMovieCachaProvider.Add(aMovieName.GetHashCode().ToString(), aPlaytimeItem.Movie, DateTime.Now.AddDays(2));
        //                        aMovieCachaProvider.Add(aPlaytimeItem.Movie.Id.ToString(), aPlaytimeItem.Movie, DateTime.Now.AddDays(2));
        //                    }
        //                    else
        //                    {
        //                        aPlaytimeItem.Movie = aMovieCache;
        //                    }

        //                    aPlaytimeItem.Movie.Title = aMovieName;



        //                    var aStartTimes = aTempImportPlaytime.Where(p => p.MovieName == aMovieName).Select(p => p.StartTime);
        //                    aStartTimes = aStartTimes.OrderBy<string, string>((p) => { return p; });

        //                    aStartTimes.ToList().ForEach(p => aPlaytimeItem.PlayTime += " " + p);


        //                    if (aPlaytimeItem.PlayTime.Length != 0)
        //                    {
        //                        aPlaytimeItem.PlayTime = aPlaytimeItem.PlayTime.Substring(1);
        //                    }

        //                    aPlaytime.Movies.Add(aPlaytimeItem);
        //                }
        //            }
        //        }
        //    }
        //    return aPlaytimeLine;
        //} 
        #endregion
    }
}